// copyright jyz.2024


#include "UI/WidgetController/OverlayWidgetController.h"

#include "AbilitySystem/AuraAbilitySystemComponent.h"
#include "AbilitySystem/AuraAttributeSet.h"



void UOverlayWidgetController::BroadcastInitialValues()
{
	const UAuraAttributeSet* AuraAttributeSet = CastChecked<UAuraAttributeSet>(AttributeSet);
	OnHealthChange.Broadcast(AuraAttributeSet->GetHealth());
	OnMaxHealthChange.Broadcast(AuraAttributeSet->GetMaxHealth());
	OnManaChange.Broadcast(AuraAttributeSet->GetMana());
	OnMaxManaChange.Broadcast(AuraAttributeSet->GetMaxMana());

	FOnGameplayAttributeValueChange&HealthValueChange = AbilitySystemComponent->GetGameplayAttributeValueChangeDelegate(AuraAttributeSet->GetHealthAttribute());
	HealthValueChange.AddLambda([this](const FOnAttributeChangeData& Data){	OnHealthChange.Broadcast(Data.NewValue);});

	FOnGameplayAttributeValueChange&MaxHealthValueChange = AbilitySystemComponent->GetGameplayAttributeValueChangeDelegate(AuraAttributeSet->GetMaxHealthAttribute());
	MaxHealthValueChange.AddLambda([this](const FOnAttributeChangeData& Data){	OnMaxHealthChange.Broadcast(Data.NewValue);});
	
	FOnGameplayAttributeValueChange&ManaValueChange = AbilitySystemComponent->GetGameplayAttributeValueChangeDelegate(AuraAttributeSet->GetManaAttribute());
	ManaValueChange.AddLambda([this](const FOnAttributeChangeData& Data){	OnManaChange.Broadcast(Data.NewValue);});

	FOnGameplayAttributeValueChange&MaxManaValueChange = AbilitySystemComponent->GetGameplayAttributeValueChangeDelegate(AuraAttributeSet->GetMaxManaAttribute());
	MaxManaValueChange.AddLambda([this](const FOnAttributeChangeData& Data){	OnMaxManaChange.Broadcast(Data.NewValue);});

	//GameplayTag 相关代理绑定
	UAuraAbilitySystemComponent* AuraASC = Cast<UAuraAbilitySystemComponent>(AbilitySystemComponent);
	checkf(AuraASC,TEXT("AuraASC is nullptr"));
	AuraASC->EffectAssetTagsDelegate.AddUObject(this,&UOverlayWidgetController::OnEffectAssetTags);
}


void UOverlayWidgetController::OnEffectAssetTags(const FGameplayTagContainer& InAssetTags)
{
	FGameplayTag MessageTag = FGameplayTag::RequestGameplayTag(FName("Message"));
	for(const FGameplayTag& Tag : InAssetTags)
	{
		//"A.1".MatchesTag("A") will return True, "A".MatchesTag("A.1") will return False
		if(!Tag.MatchesTag(MessageTag))
			continue;
		if(FUIWidgetRow*UIWidgetRow = GetDataTableRowByTag<FUIWidgetRow>(MessageWidgetDataTable,Tag))
		{
			OnMessageWidget.Broadcast(*UIWidgetRow);
		}
	}
	
}
